package p2pscrabble;

import java.awt.TextArea;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.GroupLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ChatPanel extends JPanel {

	private TextArea messageArea;
	private JTextField chatField;
	Game g;

	KeyAdapter chatEnter = new KeyAdapter() {

		@Override
		public void keyTyped(KeyEvent e) {
		}

		@Override
		public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				if (chatField.getText().equals("")) {
					chatField.setText("");
					return;
				}
				String s = g.amIPlayer1() ? g.player1 + ": "
						+ chatField.getText() : g.player2 + ": "
						+ chatField.getText();

				g.sendChatMessage(s);

				appendMessage(s, true);

				chatField.setText("");
			}
		}
	};

	public ChatPanel(Game g) {
		this.g = g;

		messageArea = new TextArea(null, 2, 10, TextArea.SCROLLBARS_VERTICAL_ONLY);
		chatField = new JTextField(10);
		messageArea.setEditable(false);
		chatField.setEditable(true);

		this.add(messageArea);
		this.add(chatField);

		GroupLayout layout = new javax.swing.GroupLayout(this);
		this.setLayout(layout);

		layout.setHorizontalGroup(layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				messageArea, javax.swing.GroupLayout.DEFAULT_SIZE, 360,
				Short.MAX_VALUE).addComponent(chatField,
				javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE));

		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addComponent(
												messageArea,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												100,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												chatField,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addContainerGap()));

		chatField.addKeyListener(chatEnter);
	}

	public void appendMessage(String s, boolean me) {
		s = me? "(me)" + s: s;
		messageArea.setText(messageArea.getText() + "\n" + s);
	}

}
